<template>
  <div class="user-management">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <h2>用户管理</h2>
          <el-button type="primary" @click="loadUsers">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </template>

      <!-- 搜索栏 -->
      <el-row :gutter="20" class="search-bar">
        <el-col :span="8">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索用户名、邮箱"
            clearable
            @clear="loadUsers"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
            <template #append>
              <el-button @click="handleSearch">搜索</el-button>
            </template>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-select v-model="filterRole" placeholder="筛选角色" clearable @change="handleSearch">
            <el-option label="管理员" value="ADMIN" />
            <el-option label="普通用户" value="USER" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select v-model="filterStatus" placeholder="筛选状态" clearable @change="handleSearch">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-col>
      </el-row>

      <!-- 用户列表表格 -->
      <el-table
        :data="users"
        v-loading="loading"
        stripe
        style="width: 100%"
        @sort-change="handleSortChange"
      >
        <el-table-column prop="id" label="ID" width="80" sortable="custom" />
        <el-table-column prop="username" label="用户名" min-width="120" />
        <el-table-column prop="email" label="邮箱" min-width="180" />
        <el-table-column prop="nickname" label="昵称" min-width="100" />
        <el-table-column prop="role" label="角色" width="100">
          <template #default="{ row }">
            <el-tag :type="row.role === 'ADMIN' ? 'danger' : 'info'">
              {{ row.role === 'ADMIN' ? '管理员' : '普通用户' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="注册时间" min-width="160" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleEditRole(row)">
              修改角色
            </el-button>
            <el-button
              size="small"
              :type="row.status === 1 ? 'danger' : 'success'"
              @click="handleToggleStatus(row)"
            >
              {{ row.status === 1 ? '禁用' : '启用' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="loadUsers"
        @current-change="loadUsers"
      />
    </el-card>

    <!-- 修改角色对话框 -->
    <el-dialog
      v-model="showRoleDialog"
      title="修改用户角色"
      width="400px"
      @close="selectedUser = null"
    >
      <el-form label-width="100px">
        <el-form-item label="用户名">
          <el-input :value="selectedUser?.username" disabled />
        </el-form-item>
        <el-form-item label="当前角色">
          <el-tag :type="selectedUser?.role === 'ADMIN' ? 'danger' : 'info'">
            {{ selectedUser?.role === 'ADMIN' ? '管理员' : '普通用户' }}
          </el-tag>
        </el-form-item>
        <el-form-item label="新角色">
          <el-radio-group v-model="newRole">
            <el-radio label="ADMIN">管理员</el-radio>
            <el-radio label="USER">普通用户</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showRoleDialog = false">取消</el-button>
        <el-button type="primary" @click="handleConfirmRoleChange">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { adminApi } from '@/services/adminApi'
import { Refresh, Search } from '@element-plus/icons-vue'

const users = ref([])
const loading = ref(false)
const searchKeyword = ref('')
const filterRole = ref('')
const filterStatus = ref('')
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

// 修改角色相关
const showRoleDialog = ref(false)
const selectedUser = ref(null)
const newRole = ref('')

// 加载用户列表
const loadUsers = async () => {
  loading.value = true
  try {
    const params = {
      current: currentPage.value,
      size: pageSize.value
    }
    
    // 添加搜索参数
    if (searchKeyword.value) {
      params.keyword = searchKeyword.value
    }
    if (filterRole.value) {
      params.role = filterRole.value
    }
    if (filterStatus.value !== '') {
      params.status = filterStatus.value
    }
    
    const response = await adminApi.getUserList(params)
    
    users.value = response.records || []
    total.value = response.total || 0
  } catch (error) {
    console.error('加载用户列表失败:', error)
    ElMessage.error('加载失败: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  loadUsers()
}

// 排序
const handleSortChange = ({ column, prop, order }) => {
  console.log('排序:', prop, order)
}

// 修改角色
const handleEditRole = (user) => {
  selectedUser.value = user
  newRole.value = user.role
  showRoleDialog.value = true
}

// 确认修改角色
const handleConfirmRoleChange = async () => {
  try {
    await adminApi.updateUserRole(selectedUser.value.id, newRole.value)
    
    ElMessage.success('角色修改成功')
    showRoleDialog.value = false
    loadUsers()
  } catch (error) {
    console.error('修改角色失败:', error)
    ElMessage.error('修改失败: ' + (error.message || '未知错误'))
  }
}

// 切换状态
const handleToggleStatus = async (user) => {
  try {
    await ElMessageBox.confirm(
      `确定要${user.status === 1 ? '禁用' : '启用'}用户 ${user.username} 吗？`,
      '确认操作',
      {
        type: 'warning'
      }
    )
    
    const newStatus = user.status === 1 ? 0 : 1
    await adminApi.updateUserStatus(user.id, newStatus)
    
    ElMessage.success('操作成功')
    loadUsers()
  } catch (error) {
    console.error('操作失败:', error)
    if (error.message && !error.message.includes('取消')) {
      ElMessage.error('操作失败: ' + (error.message || '未知错误'))
    }
  }
}

onMounted(() => {
  loadUsers()
})
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
}

.search-bar {
  margin-bottom: 20px;
}

.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}
</style>

